//
//  SSDKEventManager.m
//  SuperSDK
//
//  Created by wyht－ios－dev on 16/7/18.
//  Copyright © 2016年 WYHT. All rights reserved.
//

#import "SSDKEventManager.h"
#import "SSDKDataKeys.h"
#import "SSDKEventKeys.h"
#import "SDKProtocol.h"
#import "SuperSDKPluginTools/SSDKPluginLogUtil.h"

@implementation SSDKEventManager

static SSDKEventManager *instance = nil;
static NSString *KEY_SSDK_CONFIG = @"SSDKConfig";
static NSString *KEY_SDK_CLASS=@"SDK_CLASS";
static NSString *KEY_PLUG_IN=@"SSDK_PLUG_IN";
static NSString *EVENT_RECORD=@"_Event";

+ (id) getInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

//添加事件监听
+ (void) addObsver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender className:(NSString *)className {
    [[NSNotificationCenter defaultCenter] addObserver:notificationObserver selector:notificationSelector name:notificationName object:notificationSender];
    if([[SSDKEventManager getInstance] eventRecord]==nil) {
        [[SSDKEventManager getInstance] setEventRecord:[[NSMutableDictionary alloc] init]];
    }
    if(![[[[SSDKEventManager getInstance] eventRecord] allKeys] containsObject:className]) {
        [[[SSDKEventManager getInstance] eventRecord] setObject:notificationObserver forKey:className];
        [[[SSDKEventManager getInstance] eventRecord] setObject:[[NSMutableArray alloc] init] forKey:[className stringByAppendingString:EVENT_RECORD]];
    }
    NSMutableArray *classEventRecord=[[[SSDKEventManager getInstance] eventRecord] objectForKey:[className stringByAppendingString:EVENT_RECORD]];
    if(![classEventRecord containsObject:notificationName])
        [classEventRecord addObject:notificationName];
    [[[SSDKEventManager getInstance] eventRecord] setObject:classEventRecord forKey:[className stringByAppendingString:EVENT_RECORD]];
}

//查询是否监听了事件
+ (BOOL) isSupportEvent:(NSString *)className eventName:(NSString *)eventName {
    if(className==nil)
        return NO;
    if ([eventName isEqualToString:EVENT_SUBMITDATA]) {
        //强制要求监听上报事件
        return YES;
    }
    if([[SSDKEventManager getInstance] eventRecord]!=nil) {
        NSMutableArray *classEventRecord=[[[SSDKEventManager getInstance] eventRecord] objectForKey:[className stringByAppendingString:EVENT_RECORD]];
        if(classEventRecord!=nil) {
            if([classEventRecord containsObject:eventName])
                return YES;
            else
                return NO;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

+ (void) postNotificationName:(NSString *)aName object:(id)anObject {
    [SSDKEventManager initAllObject];
    [[NSNotificationCenter defaultCenter] postNotificationName:aName object:anObject];
}

//post第一个消息前初始化所有的对象，并注册绑定
+ (void) initAllObject {
    if([[SSDKEventManager getInstance] eventRecord]==nil) {
        [[SSDKEventManager getInstance] setEventRecord:[[NSMutableDictionary alloc] init]];
    }
    //检查是否有未初始化的对象,依据Plist中添加的对象进行注册绑定
    NSDictionary *data = [[NSBundle mainBundle] infoDictionary];
    NSString *baseClassName=nil;
    NSDictionary *config = [data objectForKey:KEY_SSDK_CONFIG];
    baseClassName=[config valueForKey:KEY_SDK_CLASS];
    //只初始化的时候执行一次
    if([[SSDKEventManager getInstance] targetSdkName]==nil) {
        if(baseClassName==nil) {
            return;
        }
        [SSDKPluginLogUtil Log:[@"Load sdkClass: " stringByAppendingString:baseClassName]];
        //加载"${SDK_CLASS}"配置的SDK实现类
        [[SSDKEventManager getInstance] setTargetSdkName:baseClassName];
        if(![[[[SSDKEventManager getInstance] eventRecord] allKeys] containsObject:baseClassName]) {
            id<SDKProtocol> sdk=[[NSClassFromString(baseClassName) alloc] init];
            [[[SSDKEventManager getInstance] eventRecord] setObject:sdk forKey:baseClassName];
            //"${SDK_CLASS}_Event"是SDK实现类的所有注册事件的集合
            [[[SSDKEventManager getInstance] eventRecord] setObject:[[NSMutableArray alloc] init] forKey:[baseClassName stringByAppendingString:EVENT_RECORD]];
            //调用SDK实现类的initInfo方法，进行初始化操作
            [sdk initInfo];
        }
        //加载"${SSDK_PLUG_IN}"配置的所有插件实现类
        NSMutableArray *plugIn = [config objectForKey:KEY_PLUG_IN];
        if (plugIn == nil) {
            plugIn = [[NSMutableArray alloc] init];
        } else {
            plugIn = [[NSMutableArray alloc] initWithArray:plugIn];
        }
        //加载SuperSDKConnector
        [plugIn addObject:@"SuperSDKConnector"];
        //强制加载SSDKTrace插件
        [plugIn addObject:@"SSDKTrace"];
        //强制加载SSDKRealTimeTrace插件
        [plugIn addObject:@"SSDKRealTimeTrace"];
        //强制加载SSDKHeartbeat插件
        [plugIn addObject:@"SSDKHeartbeat"];
        for (NSString *plugName in plugIn) {
            if(![[[[SSDKEventManager getInstance] eventRecord] allKeys] containsObject:plugName]) {
                [SSDKPluginLogUtil Log:[@"Load plugin: " stringByAppendingString:plugName]];
                id<SDKProtocol> plugClass =[[NSClassFromString(plugName) alloc] init];
                if (plugClass == nil) {
                    [SSDKPluginLogUtil Log:[@"Load plugin fail! null pluin: " stringByAppendingString:plugName]];
                    continue;
                }
                [[[SSDKEventManager getInstance] eventRecord] setObject:plugClass forKey:plugName];
                //"${SSDK_PLUG_IN}_Event"是Plugin实现类的所有注册事件的集合
                [[[SSDKEventManager getInstance] eventRecord] setObject:[[NSMutableArray alloc] init] forKey:[plugName stringByAppendingString:EVENT_RECORD]];
                //调用Plugin实现类的initInfo方法，进行初始化操作
                [plugClass initInfo];
            }
        }
    }
}

//下面需要返回值的情况，暂时只处理targetSDK的接口
+ (BOOL) application:(id)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    [SSDKPluginLogUtil Log:@"SSDK application:(id)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation "];
    [SSDKEventManager initAllObject];
    if ((id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]]!=nil && [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] respondsToSelector:NSSelectorFromString(@"application:openURL:sourceApplication:annotation:")]) {
        return [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    }
    
    return NO;
}

+ (BOOL) application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    [SSDKPluginLogUtil Log:@"SSDK application:(UIApplication *)application handleOpenURL:(NSURL *)url"];
    [SSDKEventManager initAllObject];
    if ((id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]]!=nil && [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] respondsToSelector:NSSelectorFromString(@"application:handleOpenURL:")]) {
        return [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] application:application handleOpenURL:url];
    }
    
    return NO;
}

+ (BOOL) application:(id)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    
    [SSDKPluginLogUtil Log:@"SSDK application:(id)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options"];
    [SSDKEventManager initAllObject];
    if ((id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]]!=nil && [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] respondsToSelector:NSSelectorFromString(@"application:openURL:options:")]) {
        return [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] application:app openURL:url options:options];
    }
    
    return NO;
}

+ (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [SSDKEventManager initAllObject];
    if ((id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]]!=nil && [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] respondsToSelector:NSSelectorFromString(@"application:didFinishLaunchingWithOptions:")]) {
        return [(id<SDKProtocol>)[[[SSDKEventManager getInstance] eventRecord] objectForKey:[[SSDKEventManager getInstance] targetSdkName]] application:application didFinishLaunchingWithOptions:launchOptions];
    }
    
    return YES;
}

@end
